<template>
  <n-layout-header class="w-full bg-dark border-b border-white/20 flex justify-center xs:h-11 m:h-14">
    <div class="header-content h-full inline-flex items-center justify-between px-3">
      <n-button :focusable="false" class="xs:visible m:invisible" text @click="chatStore.showChatSiderDrawer = true">
        <n-icon :component="MenuOutline" size="26" />
      </n-button>
      <n-ellipsis class="text-[#d9d9e3] px-8 xs:text-base m:text-md" :tooltip="false">
        {{ ['dialogue', 'chat'].includes($route.name) ? chatStore.chatTitle : $route.meta.title }}
      </n-ellipsis>
      <div class="header-extra">
        <div class="header-extra-item">
          <n-button
            v-if="mainStore.theme === 'light'"
            title="切换深色"
            :focusable="false"
            text
            @click="changeTheme('dark')"
          >
            <n-icon :component="MoonOutline" size="26" />
          </n-button>
          <n-button v-else title="切换浅色" :focusable="false" text @click="changeTheme('light')">
            <n-icon :component="SunnyOutline" size="26" />
          </n-button>
        </div>
        <div v-if="$route.name === 'dialogue' && !chatStore.isNewChat" class="header-extra-item">
          <n-button v-if="isWeiXin()" :focusable="false" text @click="chatStore.openNewChat">
            <n-icon :component="AddOutline" size="26" />
          </n-button>
          <n-dropdown v-else :options="headerState.exportOptions" @select="handleSelect">
            <n-button text title="导出会话" :focusable="false">
              <n-icon :component="DownloadOutline" size="26" />
            </n-button>
          </n-dropdown>
        </div>
      </div>
    </div>
  </n-layout-header>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { onBeforeRouteUpdate, useRoute } from 'vue-router'
import { AddOutline, MenuOutline, DownloadOutline, SunnyOutline, MoonOutline } from '@vicons/ionicons5'
import { useChatStore, useMainStore, useUserStore } from '@/store'
import { isWeiXin, timeFormat } from '@/utils'

const mainStore = useMainStore()
const chatStore = useChatStore()
const userStore = useUserStore()
const route = useRoute()

const headerState = reactive({
  exportOptions: [
    {
      label: '导出.json文件',
      key: 'json',
      prefix: 'text/json',
    },
    {
      label: '导出.txt文本',
      key: 'txt',
      prefix: 'text/plain',
    },
    {
      label: '导出.md文档',
      key: 'md',
      prefix: 'text/plain',
    },
  ],
})

onBeforeRouteUpdate(route => {
  changeWidth(route.name)
})

const changeTheme = theme => {
  mainStore.setTheme(theme)
  chatStore.closeChatSiderDrawer()
}

let width = ref('1024px')
const changeWidth = name => {
  switch (name) {
    case 'plan':
      width.value = '1224px'
      break
    default:
      width.value = '1024px'
      break
  }
}
changeWidth(route.name)

const handleSelect = (key, option) => {
  if (userStore.edition === 'plus') {
    const { prefix } = option
    const chatRoleName = chatStore.roleList[chatStore.selectRoleKey].name
    let formattedData = ''
    if (key === 'json') {
      formattedData = JSON.stringify(chatStore.content, null, 2)
    } else {
      chatStore.content.forEach(item => {
        const name = item.role === 'user' ? item.role : chatRoleName
        const sendTime = timeFormat(item.sendTime)
        formattedData += `## ${name} ${sendTime} ##\n\n${item.content}\n\n`
      })
    }
    let dataUrl = `data:${prefix};charset=utf-8,${encodeURIComponent(formattedData)}`
    const downloadAnchorNode = document.createElement('a')
    downloadAnchorNode.setAttribute('href', dataUrl)
    const fileName = chatStore.chatTitle || 'messages'
    downloadAnchorNode.setAttribute('download', `${fileName}.${key}`)
    document.body.appendChild(downloadAnchorNode)
    downloadAnchorNode.click()
    document.body.removeChild(downloadAnchorNode)
  } else {
    $message.error('导出功能只支持套餐用户使用!', { duration: 2000 })
  }
}
</script>

<style lang="less" scoped>
.n-layout-header {
  position: sticky;
  top: 0;
  z-index: 10;

  &:deep(.header-content) {
    width: v-bind(width) !important;

    .n-button {
      color: #d9d9e3;

      &:hover {
        color: #b1b1b1;
      }
    }

    .header-extra {
      display: flex;
      align-items: center;
      gap: 16px;

      .header-extra-item {
        display: flex;
        align-items: center;
      }
    }
  }

  @media only screen and (max-width: 1280px) {
    &:deep(.header-content) {
      width: 100% !important;
    }
  }
}
</style>
